<template>
  <div :class="{'mobile-batch-add-drawer':showMobilePage}">
    <el-drawer
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :with-header="false"
      class="order-setting-drawer">
      <div class="batch-title">
        <Title title="批量设置人员" font-size="16px" />
        <i class="icon el-icon-close" @click="handleClose()"/>
      </div>
      <div class="batch-container">
        <div class="batch-main">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="设置方式" prop="setMode">
              <el-select v-model="form.setMode" placeholder="请选择设置方式">
                <el-option :value="0" label="替换指定人员" />
                <el-option :value="1" label="指定人员后面新增人员" />
                <el-option :value="2" label="移除指定人员" />
              </el-select>
            </el-form-item>
            <el-form-item label="指定人员" prop="designateId">
              <select-custom-user
                v-model="form.designateId"
                :max-num="1"
                :diy-user-item-list.sync="form.designateIdList"
                :is-error="!!getError('designateId').msg"
                :include-leaver="1"
                dialog-title="选择人员"
                class="w100"
                placeholder="请选择人员"
                @change="selectUser($event, 'designateId')" />
            </el-form-item>
            <el-form-item v-if="form.setMode === 0" label="替换人员" prop="replaceId">
              <select-custom-user
                v-model="form.replaceId"
                :max-num="1"
                :diy-user-item-list.sync="form.replaceIdList"
                :is-error="!!getError('replaceId').msg"
                dialog-title="选择人员"
                class="w100"
                placeholder="请选择人员"
                @change="selectUser($event, 'replaceId')" />
            </el-form-item>
            <el-form-item v-if="form.setMode === 1" label="新增人员" prop="newId">
              <select-custom-user
                v-model="form.newId"
                :diy-user-item-list.sync="form.newIdList"
                :is-error="!!getError('newId').msg"
                :max-num="1"
                dialog-title="选择人员"
                class="w100"
                placeholder="请选择人员"
                @change="selectUser($event, 'newId')" />
            </el-form-item>
            <el-form-item label="执行流程" prop="processId">
              <el-select v-model="form.processId" filterable popper-class="width260" placeholder="请选择要执行批量设置人员的流程" multiple collapse-tags @change="selProcessId">
                <el-option
                  v-for="(item, index) in processList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                  :title="item.name"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="batch-bottom">
          <el-button type="primary" size="small" @click="handleConfirm()">确认</el-button>
          <el-button class="cancel-btn-style" size="small" type="info" @click="handleClose()">取消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Title from '@/components/Title';
import selectCustomUser from '../model/selectCustomUser';
import { processBatchSet } from '@/api/legal';
import ElMessage from '@/utils/message';
import { mapState } from 'vuex';

export default {
  name: 'BatchAdd',
  components: { Title, selectCustomUser },
  props: {
    processList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      form: {
        setMode: 0,
        designateId: [],
        replaceId: [],
        newId: [],
        processId: []
      },
      rules: {
        setMode: [{ required: true, trigger: 'change', message: '请选择设置方式' }],
        designateId: [{ required: true, trigger: 'blur', message: '请选择指定人员' }],
        replaceId: [{ required: true, trigger: 'blur', message: '请选择替换人员' }],
        newId: [{ required: true, trigger: 'blur', message: '请选择新增人员' }],
        processId: [{ required: true, trigger: 'change', message: '请选择流程' }]
      },
      errorRolesIds: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    openDialog() {
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
      this.dialogVisible = true;
    },
    handleClose() {
      this.form = {
        setMode: 0,
        designateId: [],
        replaceId: [],
        newId: [],
        processId: ''
      };
      this.dialogVisible = false;
      this.processList.forEach(item => {
        item.disabled = false;
      });
      this.$refs.form.clearValidate();
      this.removeError();
    },
    handelError() {
      if (this.form.designateId.length === 0) {
        this.errorRolesIds.push({ type: 'designateId', id: 0, left: 172 * 2 + 'px', msg: '请选择指定人员' });
      }
      if (this.form.replaceId.length === 0) {
        this.errorRolesIds.push({ type: 'replaceId', id: 1, left: 172 * 2 + 'px', msg: '请选择替换人员' });
      }
      if (this.form.newId.length === 0) {
        this.errorRolesIds.push({ type: 'newId', id: 2, left: 172 * 2 + 'px', msg: '请选择新增人员' });
      }
    },
    getError(type, id) {
      if (this.errorRolesIds.length <= 0) return {};
      return this.errorRolesIds.find(i => i.type === type && ((!id && id !== 0) || i.id === id)) || {};
    },
    removeError(type) {
      if (type) {
        this.errorRolesIds = this.errorRolesIds.filter(item => {
          return item.type !== type;
        });
      } else {
        this.errorRolesIds = [];
      }
    },
    handleConfirm() {
      this.handelError();
      this.$refs.form.validate(valid => {
        if (valid) {
          const params = {
            setMode: this.form.setMode,
            designateId: this.form.designateId[0],
            processId: this.form.processId.join(',')
          };
          if (this.form.setMode === 0) {
            params.replaceId = this.form.replaceId[0];
          } else if (this.form.setMode === 1) {
            params.newId = this.form.newId[0];
          }
          processBatchSet(params).then(res => {
            ElMessage.success(res.message);
            this.handleClose();
          }).catch(err => {
            console.log(err);
            this.handleClose();
          });
        } else {
          return false;
        }
      });
    },
    selProcessId(val) {
      if (val.includes(-1)) {
        this.form.processId = [-1];
        this.processList.forEach(item => {
          item.id && (item.disabled = true);
        });
      } else if (val.length === 0) {
        this.processList.forEach(item => {
          item.disabled = false;
        });
      }
    },
    selectUser(val, field) {
      if (val.length > 0) {
        const fields = this.$refs['form'].fields;
        fields.map(i => {
          // 通过prop属性值相同来判断是哪个输入框，比如：要移除prop为'user'
          if (i._props.prop === field) {
            i.clearValidate();
            this.removeError(field);
            return false;
          }
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.batch-title{
  display: flex;
  height: 50px;
  padding: 0 24px;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
  .icon {
    font-size: 18px;
    color: #999;
    cursor: pointer;
  }
}
.batch-container{
  padding: 17px 24px;
  .el-form{
    .el-form-item{
      width: 100%;
      .el-select{
        width: 100%;
        ::v-deep .el-input__inner{
          height: 32px;
        }
      }
      .w100{
        width: 100%;
      }
    }
  }
  .batch-bottom{
    position: fixed;
    bottom: 16px;
    text-align: center;
  }
}
.el-select-dropdown__item{
  max-width: 100% !important;
}
::v-deep .el-tag.el-tag--info{
  background: #eff3fb;
  .el-select__tags-text{
    color: #333;
  }
}
.mobile-batch-add-drawer {
  ::v-deep .el-drawer {
    width: 90vw !important;
    max-width: 400px;
  }
}
.width260 {
  .el-select-dropdown__item {
    width: 260px !important;
  }
}
</style>
